<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/7 0007
 * Time: 下午 3:28
 */

namespace common\models\QrcodeLog;


use common\components\DataHelper;

class QrcodeLog extends QrcodeLogBase
{
    public static $EXTENDS_JSON_NAME = "extra_data";


    // 是否已扫码：已扫
    const SCAN_YES = 1;
    // 是否已扫码：未扫（默认）
    const SCAN_NO = 0;
    const SCAN_FAIL = 2;

    // 用户类型:普通用户 admin表
    const USER_TYPE_ADMIN = 0;
    // 用户类型:代理商 agent表
    const USER_TYPE_AGENT = 1;
    // 用户类型:区域经理
    const USER_TYPE_MANGER = 2;

    //无类型
    const USER_TYPE_NIL = -1;

    // 二维码的类型：微信登录
    const TYPE_WX_PUBLIC = 1;


    // 二维码有效时长: 330秒
    const VALID_DURATION = 330;

    const EXTENDS_JSON_KEY_VERIFY_CODE = "verify_code";
    const EXTENDS_JSON_KEY_WX_PUBLIC_ID = "wx_public_id";

    public function beforeSave($insert)
    {
        $this->updated_time = DataHelper::date();
        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }

    public static function add($userType, $type, $userId = 0, array $extraData = [], $ip = null)
    {
        $self = new self();
        $self->ip = $ip ? $ip : DataHelper::getIp();
        $self->user_type = $userType;
        $self->type = $type;
        $self->extra_data = json_encode($extraData);
        $self->created_time = DataHelper::date();

        if ( $userId ) {
            $self->user_id = $userId;
        }

        if ( $self->insert(0) ) {
            return $self;
        }
        return false;
    }

    public function isScan()
    {
        return $this->scan == self::SCAN_YES;
    }

    public function markSuccess($openId, $userInfo = [])
    {
        $this->scan = QrcodeLog::SCAN_YES;
        $this->wechat_open_id = $openId;
        $this->wechat_user_info = is_array($userInfo) ? json_encode($userInfo) : $userInfo;
        return $this->update(0);
    }

    public function markFail()
    {
        $this->scan = QrcodeLog::SCAN_FAIL;
        return $this->update(0);
    }
}